package com.jawmask.android.discover.bean.task;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import com.jawmask.android.discover.R;

public class FetchImageTask extends BaseDiscoverTask<String, Void, Bitmap> {

	private final ImageView imageView;
	private String imagePath;

	public FetchImageTask(final Context context, final ImageView imageView) {
		super(context);
		this.imageView = imageView;
	}

	@Override
	protected Bitmap doInBackground(String... parameter) {

		try {
			HttpClient httpClient = new DefaultHttpClient();

			imagePath = parameter[0];

			HttpGet httpGet = new HttpGet(imagePath);

			HttpResponse httpResponse = httpClient.execute(httpGet);

			Bitmap bitmap = BitmapFactory.decodeStream(httpResponse.getEntity().getContent());

			httpClient.getConnectionManager().shutdown();

			return bitmap;

		} catch (IOException e) {
		}
		return null;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (!imageView.getTag().toString().equals(imagePath)) {
			return;
		}

		if (result != null)
			imageView.setImageBitmap(result);
		else {
			Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.soniq_no_product_logo);
			imageView.setImageBitmap(bitmap);
		}
	}

	@Override
	protected URI getRequestURI(String... parameter) throws URISyntaxException {
		return null;
	}

	@Override
	protected Bitmap getObjectFromJSON(JSONObject searchResultsJson) throws JSONException {
		return null;
	}
}
